import Vue from "vue";
import axios from "axios";

let propName;
export default function webSocketWithServer(item, url, prop) {
    //将事件监听绑定在服务器单项上以便获取后端传输的数据
    let webSocket = new WebSocket(url);
    //open不绑定是因为让函数内的指针默认为webSocket,这样就可以直接用this来获得webSocket指针对象
    webSocket.addEventListener('open', socketOpenHandler.bind(item), false);
    webSocket.addEventListener('close', socketCloseHandler.bind(item), false);
    webSocket.addEventListener('error', socketErrorHandler.bind(item), false);
    webSocket.addEventListener('message', socketMessageHandler.bind(item), false);
    item.webSocket = webSocket;
    propName = prop;
    return item;
}

function socketOpenHandler(e) {
    //有数据响应说明可用
    this.enable = true;
    //获取队列状态
    this.webSocket.send('sendQueue');
    //将本来的请求路径保存
    let baseURL = axios.defaults.baseURL;
    //临时请求路径
    axios.defaults.baseURL = `${this.protocol}://${this.ip}${this.port ? ':' + this.port : ''}/${this.ip === 'localhost' ? '' : 'email-tool-back'}/`;
    axios.get('emailPushModule/getQueueStatus', {timeout: 10000}).then((rs) => {
        //响应性赋值,避免视图不显示
        Vue.set(this, 'sendQueue', rs.data);
    }).catch((e) => {
        console.error(`获取${this.ip}的队列时出现错误 : ` + e.message);
    });
    //恢复基本路径
    axios.defaults.baseURL = baseURL;
    console.log(`%c-${this.ip}-webSocket已连接`, 'background:#0d3f67;color:#1ee3cf;font-weight:bold;font-size:1rem;');
}

function socketCloseHandler(e) {
    //如果关闭了,说明服务器不可用
    this.enable = false;
    console.log(`%c-${this.ip}-webSocket已关闭`, 'background:#0d3f67;color:#1ee3cf;font-weight:bold;font-size:1rem;');
}

function socketErrorHandler(e) {
    console.log(`%c-${this.ip}-webSocket出现异常`, 'background:#0d3f67;color:#1ee3cf;font-weight:bold;font-size:1rem;');
}

function socketMessageHandler(e) {
    //将响应数据绑定到属性上
    Vue.set(this, propName, JSON.parse(e.data));
}